#include <stdio.h>
#include <stdlib.h>
#include <libexif/exif-data.h>
#include <libexif/exif-entry.h>

// 打印 EXIF 中的 GPS 信息
void print_gps_info(ExifData *ed) {
    ExifEntry *entry;
    char buf[256];

    // 获取 GPS 信息
    entry = exif_data_get_entry(ed, EXIF_TAG_GPS_LATITUDE);
    if (entry) {
        exif_entry_get_value(entry, buf, sizeof(buf));
        printf("GPS Latitude: %s\n", buf);
    }

    entry = exif_data_get_entry(ed, EXIF_TAG_GPS_LONGITUDE);
    if (entry) {
        exif_entry_get_value(entry, buf, sizeof(buf));
        printf("GPS Longitude: %s\n", buf);
    }

    entry = exif_data_get_entry(ed, EXIF_TAG_GPS_ALTITUDE);
    if (entry) {
        exif_entry_get_value(entry, buf, sizeof(buf));
        printf("GPS Altitude: %s\n", buf);
    }
}


// 回调函数，用于处理每个 EXIF 条目
void exif_entry_handler(ExifEntry *entry, void *user_data) {
    char buf[256];
    exif_entry_get_value(entry, buf, sizeof(buf));
    printf("Tag: %s, Value: %s\n", exif_tag_get_name(entry->tag), buf);
}

void print_exif_info(const char *filename) {
    ExifData *ed;

    // 读取 EXIF 数据
    ed = exif_data_new_from_file(filename);
    if (!ed) {
        fprintf(stderr, "No EXIF data found in %s\n", filename);
        return;
    }

       // 打印 GPS 信息
    print_gps_info(ed);

    printf("*****************all tag************************\n");
    // 遍历所有 IFD
    for (int i = 0; i < EXIF_IFD_COUNT; i++) {
        ExifContent *content = ed->ifd[i];
        if (content) {
            // 遍历每个 IFD 中的条目
            exif_content_foreach_entry(content, exif_entry_handler, NULL);
        }
    }

    // 释放 EXIF 数据
    exif_data_free(ed);
}
/*
void print_exif_info(const char *filename) {
    ExifData *ed;

    // 读取 EXIF 数据
    ed = exif_data_new_from_file(filename);
    if (!ed) {
        fprintf(stderr, "No EXIF data found in %s\n", filename);
        return;
    }

    // 打印 GPS 信息
    print_gps_info(ed);

    // 遍历所有 IFD
    for (int i = 0; i < EXIF_IFD_COUNT; i++) {
        ExifContent *content = ed->ifd[i];
        if (content) {
            // 遍历每个 IFD 中的条目
            for (ExifEntry *entry = content->entries; entry != NULL; entry = entry->next) {
                char buf[256];
                exif_entry_get_value(entry, buf, sizeof(buf));
                printf("Tag: %s, Value: %s\n", exif_tag_get_name(entry->tag), buf);
            }
        }
    }

    // 释放 EXIF 数据
    exif_data_free(ed);
}
*/

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <input.jpg>\n", argv[0]);
        return 1;
    }

    print_exif_info(argv[1]);
    return 0;
}